using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using MMLib.SwaggerForOcelot.Configuration;
using Leo.Core.Gateway.EntityFrameworkCore;
using Ocelot.Cache.CacheManager;
using Ocelot.Configuration.File;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using System;
using System.Collections.Generic;
using System.Linq;
using Volo.Abp;
using Volo.Abp.AspNetCore.Serilog;
using Volo.Abp.Autofac;
using Volo.Abp.Modularity;
using static System.Console;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Cors;

namespace Leo.Core.Gateway;

[DependsOn(
    typeof(GatewayApplicationModule),
    typeof(GatewayEntityFrameworkCoreModule),
    typeof(GatewayHttpApiModule),
    typeof(AbpAutofacModule),
    typeof(AbpAspNetCoreSerilogModule)
    )]
public class GatewayHttpApiHostModule : AbpModule
{

    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        var services = context.Services;

        var configuration = context.Services.GetConfiguration();

        Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} application test....");
        // 配置跨域
        ConfigureCors(context, configuration);

        services.AddOcelot()
                //.AddConsul()
                //.AddConfigStoredInConsul()
                .AddCacheManager(x =>
                {
                    x.WithDictionaryHandle();
                });

        services.AddSwaggerForOcelot(configuration);

    }
    private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
    {
        context.Services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder =>
            {
                builder
                    .WithOrigins(
                        configuration["App:CorsOrigins"]
                            .Split(",", StringSplitOptions.RemoveEmptyEntries)
                            .Select(o => o.RemovePostFix("/"))
                            .ToArray()
                    )
                    .WithAbpExposedHeaders()
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
            });
        });
    }
    public override async void OnApplicationInitialization(ApplicationInitializationContext context)
    {
        var app = context.GetApplicationBuilder();
        var env = context.GetEnvironment();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCorrelationId();

        // 启用反向代理所需的端点路由
        app.UseRouting();

        app.UseCors();

        //WriteLineInfo(app);

        app.UseEndpoints(endpoints =>
              endpoints.MapGet("/", async context =>
              {
                  var hostEnvironment = context.RequestServices.GetService<IHostEnvironment>();
                  await context.Response.WriteAsync(hostEnvironment.EnvironmentName);
              }));

        app.UseSwagger();
        await app.UseSwaggerForOcelotUI(options =>
         {
             options.PathToSwaggerGenerator = "/swagger/docs";
         }).UseOcelot();
    }

    private static void WriteLineInfo(IApplicationBuilder app)
    {
        var routeOptions = app.ApplicationServices.GetRequiredService<IOptions<List<RouteOptions>>>().Value;
        var routefirst = routeOptions.FirstOrDefault();
        var routelast = routeOptions.LastOrDefault();
        WriteLine($"第一个route的swaggerkey是：{routefirst.SwaggerKey}");
        WriteLine($"最后一个route的swaggerkey是: {routelast.SwaggerKey}");

        var swaggerEndPointOptions = app.ApplicationServices.GetRequiredService<IOptions<List<SwaggerEndPointOptions>>>().Value;
        var swaggerEndPointOptionsfirst = swaggerEndPointOptions.FirstOrDefault();
        WriteLine($"第一个url地址是:{swaggerEndPointOptionsfirst.Config[0]?.Url}");

        //var fileGlobalConfiguration = app.ApplicationServices.GetRequiredService<IOptions<FileGlobalConfiguration>>().Value;
        //WriteLine($"GlobalConfiguration 的 BaseUrl:{fileGlobalConfiguration.BaseUrl}");
        //WriteLine($"GlobalConfiguration 的 Consul地址(没带端口号) :{fileGlobalConfiguration.ServiceDiscoveryProvider.Host}");

    }
}

